from rest_framework import serializers
from ..users.models import User
from goods.models import SKUImage, SKU, SPUSpecification, SKUSpecification

# serializers.ModelSerializer

# 用户相关信息
class UserSerializers(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'mobile', 'password']
        # fields = '__all__'
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):

        return User.objects.create_user(**validated_data)


# 商品图片信息展示
class SKUIMageSerializers(serializers.ModelSerializer):

    class Meta():
        model = SKUImage

        fields = '__all__'

    def update(self, instance, validated_data):

        image_data = validated_data.get('image').read()
        from fdfs_client.client import Fdfs_client
        client = Fdfs_client('utils/fastdfs/client.conf')
        result = client.upload_by_buffer(image_data)
        if result['Status'] != 'Upload successed.':
            raise serializers.ValidationError('失败')
        file_id = result.get('Remote file_id')
        instance.image = file_id
        instance.save()
        return instance



class ShowSKUINFI(serializers.ModelSerializer):

    class Meta():

        model = SKU
        fields = ['id', 'name']


################SKU规格###########
class SKUpecificationModelserializer(serializers.ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()
    class Meta:

        model = SKUSpecification
        fields = ['spec_id', 'option_id']


class SKU_admin_CRUDSerializers(serializers.ModelSerializer):

    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()

    spu = serializers.StringRelatedField(required=False)
    category = serializers.StringRelatedField()

    specs = SKUpecificationModelserializer(many=True)

    class Meta():

        model = SKU
        fields = '__all__'

    def create(self, validated_data):

        specs = validated_data.pop('specs')

        from django.db import transaction
        with transaction.atomic():
            save_point = transaction.savepoint()
            try:
                sku = SKU.objects.create(**validated_data)
                for spec in specs:
                    SKUSpecification.objects.create(sku=sku, **spec)
            except Exception:
                transaction.savepoint_rollback(save_point)
            else:
                transaction.savepoint_commit(save_point)

        sku = SKU.objects.create(**validated_data)
        for spec in specs:
            SKUSpecification.objects.create(sku=sku, **spec)
        return sku


    def update(self, instance, validated_data):

        specs = validated_data.pop('specs')
        super().update(instance, validated_data)

        for spec in specs:
            SKUSpecification.objects.filter(sku=instance, spec_id=spec.get('spec_id')).update(option_id=spec.get('option_id'))

        return instance

from goods.models import GoodsCategory, SPU, SPUSpecification, SpecificationOption
##########三级商品序列化器###########
class Show_Categories_Serializers(serializers.ModelSerializer):

    class Meta():
        model = GoodsCategory

        fields = ['id', 'name']


####################SPU#####################
class Show_SPU_Serializers(serializers.ModelSerializer):
    class Meta():
        model = SPU
        fields = ['id', 'name']


class SpecificationOptionSerializers(serializers.ModelSerializer):

    class Meta():
        model = SpecificationOption
        fields = ['id', 'value']




class SpecsModelSerializers(serializers.ModelSerializer):

    options = SpecificationOptionSerializers(many=True)

    class Meta():
        model = SPUSpecification
        fields = ['id', 'name', 'options']




########权限序列化器############
from django.contrib.auth.models import Permission
class PermissionModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Permission
        fields = '__all__'


from django.contrib.auth.models import ContentType
class ContentTypeModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContentType
        fields = ['id', 'name']


from django.contrib.auth.models import Group
class Group_Serializer(serializers.ModelSerializer):

    class Meta:
        model = Group
        fields = '__all__'


#############用户管理员##############
from apps.users.models import User

class User_Serializer(serializers.ModelSerializer):

    class Meta:
        model = User
        # fields = ['id', 'username', 'mobile', 'email', 'password']
        fields = '__all__'

    def create(self, validated_data):

        user = super().create(validated_data)
        user.set_password(validated_data.get('password'))
        user.is_staff = True
        user.save()
        return User

#################管理员管理获取所有组的序列化器###########
class Admin_PeopleGroup(serializers.ModelSerializer):
    class Meta:
        model = Group.objects.all()
        fields = '__all__'